package com.ruoyi.project.manhua.webLook.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.qiniu.QiNiuYunUtils;
import com.ruoyi.framework.redis.RedisKey;
import com.ruoyi.framework.redis.RedisUtils;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.manhua.name.domain.MhName;
import com.ruoyi.project.manhua.name.service.IMhNameService;
import com.ruoyi.project.manhua.newXml.MhNameNewMapper;
import com.ruoyi.project.manhua.webLook.entity.MhWebName;
import com.ruoyi.project.manhua.webLook.enumClass.MhIndexEnum;
import com.ruoyi.project.manhua.webLook.service.MhIndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MhIndexServiceImpl implements MhIndexService {


    @Autowired
    private MhNameNewMapper mhNameNewMapper;

    @Autowired
    private IMhNameService iMhNameService;

    @Autowired
    private QiNiuYunUtils qiNiuYunUtils;

    @Autowired
    private RedisUtils redisUtils;

    /*启用redis开关*/
    @Value("${spring.redis.enabled}")
    private boolean enabled;

    /**
     * 封装返回数据
     *
     * @return
     */
    @Override
    public AjaxResult selectIndexData() {
        /*获取 首页数据*/
        Map<String, List<MhName>> redisIndexData = this.getRedisIndexData();
        /*封装返回*/
        AjaxResult ajaxResult = new AjaxResult();
        /*添加*/
        redisIndexData.forEach((key, value) -> {
            ajaxResult.put(key, value);
        });
        /*返回状态码*/
        ajaxResult.put(AjaxResult.CODE_TAG, AjaxResult.Type.SUCCESS.value());

        /*如果 用户信息不等于 空 将用户头像返回*/
        if (ShiroUtils.getSysUser() != null) {
            //mhNames.add(new MhName(ShiroUtils.getSysUser().getAvatar()));
            ajaxResult.put("avatar", ShiroUtils.getSysUser().getAvatar());
        }

        return ajaxResult;
    }

    /**
     * 查询阅读量最高的数据
     *
     * @return 返回数据
     */
    @Override
    public List<MhName> seletWebLimitList() {

        List<MhName> mhNames = null;

        if (enabled) {

            mhNames = (List<MhName>) redisUtils.get(RedisKey.indexRedis.sliding_data.getKey());

            if (CollectionUtils.isEmpty(mhNames)) {

                synchronized (this) {

                    mhNames = (List<MhName>) redisUtils.get(RedisKey.indexRedis.sliding_data.getKey());

                    if (CollectionUtils.isEmpty(mhNames)) {


                        mhNames = mhNameNewMapper.seletWebLimitList(new MhWebName(10, 11, MhIndexEnum.STATE.READING.getValue()));

                        mhNames.forEach((e) -> {
                            e.setTheCover(Constants.getEncoder(qiNiuYunUtils.getUrlImg(e.getTheCover())));
                        });

                        /*加入redis数据*/
                        redisUtils.set(RedisKey.indexRedis.sliding_data.getKey(), mhNames, RedisKey.time);
                    }

                }
            }


        } else {
            mhNames = mhNameNewMapper.seletWebLimitList(new MhWebName(10, 11, MhIndexEnum.STATE.READING.getValue()));
            mhNames.forEach((e) -> {
                e.setTheCover(Constants.getEncoder(qiNiuYunUtils.getUrlImg(e.getTheCover())));
            });
        }

        return mhNames;
    }

    /**
     * 获取首页所有数据
     *
     * @return
     */
    @Override
    public Map<String, List<MhName>> getRedisIndexData() {
        /*数据库中获取的数据*/
        Map<String, List<MhName>> nameMap = null;
        /*全部数据*/
        List<MhName> RedisList = null;
        /*redis中获取的数据，需要转换*/
        Map<Object, Object> mhNameMap = null;

        /*查看redis是否开启*/
        if (enabled) {
            /*获取redis中储存的数据*/
            mhNameMap = redisUtils.hmget(RedisKey.indexRedis.index_data.getKey());

            /*如果等于空*/
            if (CollectionUtils.isEmpty(mhNameMap)) {

                synchronized (this) {

                    mhNameMap = redisUtils.hmget(RedisKey.indexRedis.index_data.getKey());

                    /*还是空 获取漫画全部数据*/
                    if (CollectionUtils.isEmpty(mhNameMap)) {

                        /*全部数据*/
                        RedisList = iMhNameService.getRedisListAll();
                        /*返回排好的数据*/
                        nameMap = getIndexData(RedisList);

                        Map<String, Object> map = new HashMap<>();

                        nameMap.forEach((k, v) -> {
                            map.put(k, JSON.toJSONString(v));
                        });
                        /*添加redis中*/
                        redisUtils.hmset(RedisKey.indexRedis.index_data.getKey(), map, RedisKey.time);
                    }
                }
            }
        } else {
            /*全部数据*/
            RedisList = iMhNameService.getRedisListAll();
            nameMap = getIndexData(RedisList);
        }

        if (CollectionUtils.isEmpty(nameMap)) {
            /*创建临时map*/
            Map<String, List<MhName>> finalNameMap = new HashMap<>();
            /*循环转换*/
            mhNameMap.forEach((key, value) -> {
                finalNameMap.put(key.toString(),JSONArray.parseArray(value.toString(),MhName.class) );
            });
            /*赋值*/
            nameMap = finalNameMap;
        }
        /*返回*/
        return nameMap;
    }

    /**
     * 获取排序好的首页所有数据
     *
     * @return
     */
    @Override
    public Map<String, List<MhName>> getIndexData(List<MhName> lists) {

        /*排序出 阅读数量最多的漫画 分页前十条数据 用于index页面 轮播图使用*/
        List<MhName> slideshow = lists.stream()
                /*按照阅读量 排序*/
                .sorted(Comparator.comparing(MhName::getReading, Comparator.reverseOrder()))
                /*获取 前十条数据*/
                .limit(8)
                /*返回list 集合*/
                .collect(Collectors.toList());


        /*获取 等于国漫的前9条数据 index页面第二大行使用*/
        List<MhName> twoLine = lists.stream()
                /*获取国漫数据*/
                .filter((e) -> MhIndexEnum.COUNTRIES.CHINA.getId().equals(e.getCountriesId()))
                /*按照阅读量 排序*/
                .sorted(Comparator.comparing(MhName::getReading, Comparator.reverseOrder()))
                /*获取前6条数据*/
                .limit(9)
                /*返回list集合*/
                .collect(Collectors.toList());


        /*获取更新频繁的数据*/
        List<MhName> maxFourLine = lists.stream()
                /*更新时间排序*/
                .sorted(Comparator.comparing(MhName::getUpdateTime, Comparator.reverseOrder()))
                /*前十条数据*/
                .limit(10)
                .collect(Collectors.toList());


        List<MhName> sixEight = lists.stream()
                .sorted(Comparator.comparing(MhName::getCreateTime, Comparator.reverseOrder()))
                .limit(10)
                .collect(Collectors.toList());


        /*点赞最多的前九条数据*/
        List<MhName> getGiveLike = lists.stream()
                .sorted(Comparator.comparing(MhName::getGiveLike, Comparator.reverseOrder()))
                .limit(9)
                .collect(Collectors.toList());

        Map<String, List<MhName>> nameMap = new HashMap<>();
        /*截取前十条数据 第一大行轮播图*/
        //ajaxResult.put("slideshow", slideshow.subList(0, 10));
        /*截取后六条数据 用于第二大行6调数据*/
        nameMap.put("maxTwoLine", twoLine.subList(3, 9));
        /*后八条数据 第三大行 左边 8条数据*/
        nameMap.put("maxThreeMinOneLine", slideshow.subList(0, 8));
        /*国漫前三条数据 第三大行 右边 3条数据*/
        nameMap.put("maxThreeMinTwoLine", twoLine.subList(0, 3));
        /*第四大行*/
        nameMap.put("maxFourLine", maxFourLine);
        /*第六大行*/
        nameMap.put("six", sixEight.subList(0, 4));
        /*第七大行*/
        nameMap.put("seven", getGiveLike);
        /*第八大行*/
        nameMap.put("eight", sixEight.subList(4, 10));

        return nameMap;
    }


}
